package zxing.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.githang.statusbar.StatusBarCompat;
import com.zhihu.matisse.Matisse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.virtualapp.R;
import io.virtualapp.abs.ui.VActivity;
import io.virtualapp.bean.ResultBean;
import io.virtualapp.home.adapters.ImageChoseAdapter;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.util.HttpUtils;
import io.virtualapp.mylibrary.util.PermissionUtils;
import io.virtualapp.mylibrary.util.ToastUtils;
import io.virtualapp.mylibrary.util.Utils;
import io.virtualapp.utils.ImageUtils;
import io.virtualapp.utils.MatisseUtil;
import okhttp3.Request;
import okhttp3.Response;
import zxing.activity.adapter.TypeChoseAdapter;

public class SuAddActivity extends VActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.cl_)
    ConstraintLayout cl;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.rc_imag)
    RecyclerView rcImag;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.rc_type)
    RecyclerView rcType;
    @BindView(R.id.ll_)
    LinearLayout ll2;
    @BindView(R.id.bt_bottom)
    Button btBottom;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.iv_dis)
    ImageView ivDis;

    private ImageChoseAdapter adapter;
    private int curent_position;
    private TypeChoseAdapter adapter2;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.su_activity_su_add);


        ButterKnife.bind(this);
        initView();
    }


    private void initView() {
        initRecycleview();
        btBottom.setOnClickListener(view -> {
            UpLoadService();
        });
        ivDis.setOnClickListener(view -> {
            finish();
        });
    }

    private void initRecycleview() {
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        rcImag.setLayoutManager(manager);
        adapter = new ImageChoseAdapter(this, 3, null, new ImageChoseAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(int position) {
                curent_position = position;
                MatisseUtil.GetPhoto(SuAddActivity.this, 1, 1113, 115);
            }

            @Override
            public void OnAddItemClick(int count) {
                MatisseUtil.GetPhoto(SuAddActivity.this, count, 1113, 114);
            }
        });
        rcImag.setAdapter(adapter);


        GridLayoutManager typemanger = new GridLayoutManager(this, 3);
        rcType.setLayoutManager(typemanger);
        List<String> types = new ArrayList<>();
        types.add("程序BUG");
        types.add("内容建议");
        types.add("网络问题");
        types.add("功能建议");
        types.add("其他");
        adapter2 = new TypeChoseAdapter(types);
        rcType.setAdapter(adapter2);
        adapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                adapter2.setCurrentPosition(position);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case 114:
                    List<Uri> list2 = Matisse.obtainResult(data);
                    if (null != list2 && list2.size() > 0) {
                        List<String> strings = new ArrayList<>();
                        for (Uri uri : list2) {
                            strings.add(uri.toString());
                        }
                        adapter.AddDatas(strings);
                    }
                    break;

                case 115:
                    List<Uri> list3 = Matisse.obtainResult(data);
                    if (null != list3 && list3.size() > 0) {
                        adapter.repeleceData(list3.get(0).toString(), curent_position);
                    }
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1113)
            PermissionUtils.onRequestMorePermissionsResult(this, MatisseUtil.PICTURE_PERMISSION, new PermissionUtils.PermissionCheckCallBack() {
                @Override
                public void onHasPermission() {
                    ToastUtils.showShortToast("授权成功");
                }

                @Override
                public void onUserHasAlreadyTurnedDown(String... strings) {
                    ToastUtils.showShortToast("授予此权限才能添加照片哦,点击确定继续授权。");
                    PermissionUtils.requestMorePermissions(SuAddActivity.this, MatisseUtil.PICTURE_PERMISSION, 1113);
                   /* DialogManager.getInstanse(CreatProductActivity.this).Show2BtTipDialog(mContext,"授予此权限才能添加照片哦,点击确定继续授权。", new DialogManager.OnDialogBaseLickListener() {
                        @Override
                        public void OnDialogDis() {

                        }

                        @Override
                        public void OnDialogOk() {
                            PermissionUtils.requestMorePermissions(CreatProductActivity.this, Constant.PICTURE_PERMISSION,111);
                        }
                    });*/
                }

                @Override
                public void onUserHasAlreadyTurnedDownAndDontAsk(String... strings) {
                    ToastUtils.showShortToast("您已经拒绝授权，无法继续添加照片，点击确定进入设置开启授权");
                    PermissionUtils.toAppSetting(SuAddActivity.this);
                    /*DialogManager.getInstanse(CreatProductActivity.this).Show2BtTipDialog(mContext,"您已经拒绝授权，无法继续添加照片，点击确定进入设置开启授权", new DialogManager.OnDialogBaseLickListener() {
                        @Override
                        public void OnDialogDis() {

                        }

                        @Override
                        public void OnDialogOk() {
                            PermissionUtils.toAppSetting(CreatProductActivity.this);
                        }
                    });*/
                }
            });
    }

    private void UpLoadService() {
        String tem = etTitle.getText().toString();
        if (Utils.isEmpty(tem)) {
            ToastUtils.showShortToast("反馈标题不能为空哦");
            return;
        }

        tem = etContent.getText().toString();
        if (Utils.isEmpty(tem)) {
            ToastUtils.showShortToast("反馈内容不能为空哦");
            return;
        }

        progressBar.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {

                StringBuilder sb = new StringBuilder("");
                try {
                    for (String s : adapter.getDatas()) {
                        sb.append(ImageUtils.Bitmap2StrByBase64(ImageUtils.getBitmapFormUri(SuAddActivity.this, Uri.parse(s))));
                        sb.append(",");
                    }

                } catch (IOException e) {
                    Log.e("zeoy", "图片解析错误");
                }

                HttpUtils.getInstance().postAddService(etTitle.getText().toString(), etContent.getText().toString(), adapter2 == null ? "" : adapter2.getCurentType(), sb.toString(), new BaseCallback<ResultBean>() {
                    @Override
                    public void onRequestBefore() {

                    }

                    @Override
                    public void onFailure(Request request, Exception e) {
                        new Handler(getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                ToastUtils.showShortToast("反馈失败" + e.toString());
                            }
                        });
                    }

                    @Override
                    public void onSuccess(Response response, ResultBean o) {
                        if (o.isIssucc()) {
                            ToastUtils.showShortToast("提交成功,感谢您的反馈,有你我们会做的更好,还请您及时关注您的反馈状态哦");
                            SuAddActivity.this.setResult(RESULT_OK);
                            SuAddActivity.this.finish();
                        } else {
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    progressBar.setVisibility(View.GONE);
                                    ToastUtils.showShortToast("反馈失败" + o.getMsg());
                                }
                            });
                        }

                    }

                    @Override
                    public void onError(Response response, int errorCode, Exception e) {
                        new Handler(getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                ToastUtils.showShortToast("反馈失败" + e.toString());
                            }
                        });
                    }
                });

            }
        }).start();

    }

}
